<template>
  <div class="text-editor" ref="editor"></div>
</template>

<script>
// 引入上传图片的请求
import { upload } from '@/services/course'
import E from 'wangeditor'
export default {
  mounted () {
    this.initEditor()
  },
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      editor: null,
      // 编辑的数据是否已加载完毕
      isLoaded: false
    }
  },
  methods: {
    initEditor () {
      // 初始化富文本
      const editor = new E(this.$refs.editor)
      // 创建富文本前，进行事件设置
      editor.config.onchange = value => {
        this.$emit('input', value)
        console.log(value)
      }
      // 自己实现上传图片
      editor.config.customUploadImg = async (resultFiles, insertImgFn) => {
        // 参数1: input中上传的图片列表
        // 参数2: 获取图片URL后，插入编辑器的方法
        const fd = new FormData()
        fd.append('file', resultFiles[0])
        const { data } = await upload(fd)
        if (data.code === '000000') {
          insertImgFn(data.data.name)
        }
      }
      editor.create()
      editor.txt.html(this.value)
      this.editor = editor
    }
  },
  watch: {
    value () {
      if (!this.isLoaded) {
        this.editor.txt.html(this.value)
        this.isLoaded = true
      }
    }
  }
}

</script>
<style lang='scss' scoped>
.text-editor {
  float: left;
}
</style>
